package com.xywl.escort.view.home;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.trello.rxlifecycle2.LifecycleTransformer;
import com.xywl.escort.R;
import com.xywl.escort.adapter.HomeRvAdapter;
import com.xywl.escort.base.BaseFragment;
import com.xywl.escort.bean.BannerResp;
import com.xywl.escort.bean.BaseResp;
import com.xywl.escort.bean.IsRedPacketResp;
import com.xywl.escort.bean.MarketDataBean;
import com.xywl.escort.bean.NoticeResp;
import com.xywl.escort.bean.ProjectListResp;
import com.xywl.escort.bean.UpgradeResp;
import com.xywl.escort.entity.MultipleItem;
import com.xywl.escort.entity.NormalMultipleEntity;
import com.xywl.escort.utils.RxSPTool;
import com.xywl.escort.utils.TelephonyUtil;
import com.xywl.escort.utils.ToastUtil;
import com.xywl.escort.widget.CustomDialog3;
import com.xywl.escort.widget.UpgradeDialog;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;
import dagger.android.support.AndroidSupportInjection;
import qiu.niorgai.StatusBarCompat;
import timber.log.Timber;

import static com.xywl.escort.common.PreferenceKeys.IS_FIRST_OPEN;
import static com.xywl.escort.common.PreferenceKeys.TOKEN;
import static com.xywl.escort.common.PreferenceKeys.USER_ID;

public class HomeFragment extends BaseFragment implements HomeContract.View {
    private static final String ARG_PARAM1 = "param1";
    @Inject
    HomeContract.Presenter mPresenter;

    @BindView(R.id.recycler_list)
    RecyclerView mRecyclerView;
    @BindView(R.id.progress_bar)
    ProgressBar mProgressBar;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.img_btn_title_right)
    ImageButton mImgBtnTitleRight;
    @BindView(R.id.layout_img_btn_title_right)
    RelativeLayout mLayoutImgBtnTitleRight;
    @BindView(R.id.image_status)
    ImageView mImageStatus;

    private HomeRvAdapter multipleItemAdapter;

    public HomeFragment() {
        // Required empty public constructor
    }

    public static HomeFragment newInstance(String param1) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        AndroidSupportInjection.inject(this);
        super.onAttach(context);
    }

    @Override
    public int getLayoutResId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        if (null != this.getActivity()) {
            StatusBarCompat.translucentStatusBar(getActivity(), true);
        }
        mTvTitle.setText(getString(R.string.app_name));
        mLayoutImgBtnTitleRight.setVisibility(View.VISIBLE);
        mImgBtnTitleRight.setVisibility(View.VISIBLE);
        mImgBtnTitleRight.setImageResource(R.mipmap.home_message);

        GridLayoutManager manager = new GridLayoutManager(this.getActivity(), 4);
        mRecyclerView.setLayoutManager(manager);
    }

    @Override
    protected void initData() {
        mPresenter.takeView(this);

        int versionCode = getVersionCode();
        // 【必传】1:安卓 2:IOS
        mPresenter.upgrade(1, versionCode);

        final List<NormalMultipleEntity> data = new ArrayList<>();
        data.add(new NormalMultipleEntity(NormalMultipleEntity.BANNER));
        data.add(new NormalMultipleEntity(NormalMultipleEntity.NOTICE));
        data.add(new NormalMultipleEntity(NormalMultipleEntity.TEXT_IMG, "标局规则", R.mipmap.home_rules));
        data.add(new NormalMultipleEntity(NormalMultipleEntity.TEXT_IMG, "新手福利", R.mipmap.home_welfare));
        data.add(new NormalMultipleEntity(NormalMultipleEntity.TEXT_IMG, "出标实况", R.mipmap.home_live));
        data.add(new NormalMultipleEntity(NormalMultipleEntity.TEXT_IMG, "常见问题", R.mipmap.home_problem));
        data.add(new NormalMultipleEntity(NormalMultipleEntity.RECYCLE));
        data.add(new NormalMultipleEntity(NormalMultipleEntity.RECYCLE_GRID));

        multipleItemAdapter = new HomeRvAdapter(data);

        multipleItemAdapter.setSpanSizeLookup(new BaseQuickAdapter.SpanSizeLookup() {
            @Override
            public int getSpanSize(GridLayoutManager gridLayoutManager, int position) {
                int type = data.get(position).type;
                if (type == NormalMultipleEntity.BANNER) {
                    return MultipleItem.BANNER_SIZE;
                } else if (type == NormalMultipleEntity.NOTICE) {
                    return MultipleItem.NOTICE_SIZE;
                } else if (type == NormalMultipleEntity.RECYCLE) {
                    return MultipleItem.RECYCLE_SIZE;
                } else if (type == NormalMultipleEntity.RECYCLE_GRID) {
                    return MultipleItem.RECYCLE_SIZE;
                } else {
                    return MultipleItem.IMG_TEXT_SPAN_SIZE;
                }
            }
        });

        mRecyclerView.setAdapter(multipleItemAdapter);
    }

    private int getVersionCode() {
        int versionCode = 0;
        if (null != this.getActivity()) {
            PackageInfo packageInfo = TelephonyUtil.getAppVersionCode(this.getActivity());
            if (null != packageInfo) {
                versionCode = packageInfo.versionCode;
            }
        }
        return versionCode;
    }

    @Override
    public void onResume() {
        super.onResume();
        mPresenter.takeView(this);
        // mPresenter.loadBanner();
        String userId = "";
        if (null != this.getActivity()) {
            userId = RxSPTool.getString(this.getActivity(), USER_ID);
        }
        mPresenter.loadNotice(userId);
        mPresenter.loadProjectList(2);
        mPresenter.loadMarketList(userId);
        mPresenter.findIsNewMessage(userId);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            Timber.e("onHiddenChanged hidden");
        } else {
            Timber.e("onHiddenChanged");
            mPresenter.loadBanner();
            String userId = "";
            boolean isFirstOpen = false;
            if (null != this.getActivity()) {
                userId = RxSPTool.getString(this.getActivity(), USER_ID);
                isFirstOpen = RxSPTool.getBoolean(this.getActivity(), IS_FIRST_OPEN);
            }
            mPresenter.loadNotice(userId);
            mPresenter.loadProjectList(2);
            mPresenter.loadMarketList(userId);
            mPresenter.findIsNewMessage(userId);
            if (isFirstOpen) {
                mPresenter.isRedPacket(1);
            }
        }
    }

    @Override
    public boolean isActive() {
        return false;
    }

    @Override
    public <T> LifecycleTransformer<T> bindToLife() {
        return this.<T>bindToLifecycle();
    }

    @Override
    public void loadBannerSuccess(BannerResp resp) {
        mProgressBar.setVisibility(View.GONE);
        if (mRecyclerView.getVisibility() == View.GONE) {
            mRecyclerView.setVisibility(View.VISIBLE);
        }
        List<BannerResp.DataBean> list = resp.data;
        multipleItemAdapter.setBannerList(list);
        Timber.tag("HomeFragment").e("resp=" + resp);
    }

    @Override
    public void loadBannerFailure() {
        mProgressBar.setVisibility(View.GONE);
        if (mRecyclerView.getVisibility() == View.GONE) {
            mRecyclerView.setVisibility(View.VISIBLE);
        }
        Timber.tag("HomeFragment").e("loadBannerFailure");
    }

    @Override
    public void updateNotice(NoticeResp.DataBean dataBean) {
        mProgressBar.setVisibility(View.GONE);
        if (mRecyclerView.getVisibility() == View.GONE) {
            mRecyclerView.setVisibility(View.VISIBLE);
        }
        List<NoticeResp.DataBean.ListBean> list = new ArrayList<>();
        if (null != dataBean) {
            list.addAll(dataBean.list);
        }
        multipleItemAdapter.setNoticeList(list);
    }

    @Override
    public void loadNoticeFailure(String msg) {
        mProgressBar.setVisibility(View.GONE);
        if (mRecyclerView.getVisibility() == View.GONE) {
            mRecyclerView.setVisibility(View.VISIBLE);
        }
        Timber.tag("HomeFragment").e("loadNoticeFailure");
    }

    @Override
    public void updateProjectList(ProjectListResp.DataBean dataBean) {
        mProgressBar.setVisibility(View.GONE);
        if (mRecyclerView.getVisibility() == View.GONE) {
            mRecyclerView.setVisibility(View.VISIBLE);
        }
        List<ProjectListResp.DataBean.ListBean> list = new ArrayList<>();
        if (null != dataBean.list) {
            list.addAll(dataBean.list);
        }
        multipleItemAdapter.setProjectList(list);
    }

    @Override
    public void loadProjectFailure() {
        mProgressBar.setVisibility(View.GONE);
        if (mRecyclerView.getVisibility() == View.GONE) {
            mRecyclerView.setVisibility(View.VISIBLE);
        }
        Timber.tag("HomeFragment").e("loadProjectFailure");
    }

    @Override
    public void updateMarketList(List<MarketDataBean> dataBeans) {
        mProgressBar.setVisibility(View.GONE);
        if (mRecyclerView.getVisibility() == View.GONE) {
            mRecyclerView.setVisibility(View.VISIBLE);
        }
        List<MarketDataBean> list = new ArrayList<>();
        if (null != dataBeans) {
            list.addAll(dataBeans);
        }
        multipleItemAdapter.setMarketList(list);
    }

    @Override
    public void loadMarketFailure() {
        mProgressBar.setVisibility(View.GONE);
        if (mRecyclerView.getVisibility() == View.GONE) {
            mRecyclerView.setVisibility(View.VISIBLE);
        }
        Timber.tag("HomeFragment").e("loadMarketFailure");
    }

    @Override
    public void newMessage() {
        mImageStatus.setVisibility(View.VISIBLE);
    }

    @Override
    public void noNewMessage() {
        mImageStatus.setVisibility(View.GONE);
    }

    @Override
    public void findIsNewMessageFailure() {
        mImageStatus.setVisibility(View.GONE);
    }

    private UpgradeDialog mDialog;

    @Override
    public void hasUpgrade(final UpgradeResp.DataBean dataBean) {
        if (null != this.getActivity()) {
            String msg;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                msg = Html.fromHtml(dataBean.versionDescribe, Html.FROM_HTML_MODE_LEGACY).toString();
            } else {
                msg = Html.fromHtml(dataBean.versionDescribe).toString();
            }
            if (dataBean.isCompulsoryUpdate == 2) {
                mDialog = new UpgradeDialog.Builder(this.getActivity())
                        .setMessage(msg)
                        .setPositiveButton(R.string.go_update, R.drawable.button_dialog_green, R.color.white, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                Intent intent = new Intent();
                                intent.setAction("android.intent.action.VIEW");
                                String url = dataBean.appUrl;
                                if (!url.startsWith("https://") && !url.startsWith("http://")) {
                                    url = "http://" + url;
                                }
                                intent.setData(Uri.parse(url));
                                startActivity(intent);
                            }
                        })
                        .setCloseButton(new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                if (null != HomeFragment.this.getActivity()) {
                                    HomeFragment.this.getActivity().finish();
                                }
                            }
                        }).create();

                mDialog.setCancelable(false);
                mDialog.show();
            } else {
                mDialog = new UpgradeDialog.Builder(this.getActivity())
                        .setMessage(msg)
                        .setPositiveButton(R.string.go_update,
                                R.drawable.button_dialog_green, R.color.white, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        mDialog.dismiss();
                                        Intent intent = new Intent();
                                        intent.setAction("android.intent.action.VIEW");
                                        String url = dataBean.appUrl;
                                        if (!url.startsWith("https://") && !url.startsWith("http://")) {
                                            url = "http://" + url;
                                        }
                                        intent.setData(Uri.parse(url));
                                        startActivity(intent);
                                    }
                                })
                        .setCloseButton(null).create();
                mDialog.show();
            }
        }
    }

    private CustomDialog3 mCustomDialog3;

    @Override
    public void isRedPacketSuccess(IsRedPacketResp.DataBean dataBean) {
        if (null != this.getActivity()) {
            RxSPTool.putBoolean(this.getActivity(), IS_FIRST_OPEN, false);
            mCustomDialog3 = new CustomDialog3.Builder(HomeFragment.this.getActivity())
                    .setReceiveButton(new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            mCustomDialog3.dismiss();
                            mPresenter.processRedPacket(1);
                        }
                    })
                    .setCloseButton(null).create();
            mCustomDialog3.show();
        }
    }

    @Override
    public void isRedPacketFailure() {
        Timber.e("isRedPacketFailure");
        if (null != this.getActivity()) {
            RxSPTool.putBoolean(this.getActivity(), IS_FIRST_OPEN, false);
        }
    }

    @Override
    public void processRedPacketSuccess(BaseResp resp) {
        if (null != this.getActivity()) {
            ToastUtil.showTip(this.getActivity(), "领取成功");
        }
    }

    @Override
    public void processRedPacketFailure(String msg) {
        if (null != this.getActivity()) {
            ToastUtil.showTip(this.getActivity(), msg);
        }
    }

    @OnClick(R.id.img_btn_title_right)
    public void onViewClicked() {
        if (null != this.getActivity()) {
            String token = RxSPTool.getString(this.getActivity(), TOKEN);
            if (!TextUtils.isEmpty(token)) {
                ARouter.getInstance().build("/xy/message").navigation();
            } else {
                ARouter.getInstance().build("/xy/login").navigation();
            }
        }
    }
}
